import Vue from "vue";
import Vuex from "vuex";
import api from "./api/index.js";
import home from "./store/home";
import classify from "./store/classify";
import searchPage from "./store/searchPage";
import detail from "./store/detail";
Vue.use(Vuex);
export default new Vuex.Store({
    state:{
        history:[],
        hotWord:[],
        search:""
    },
    mutations:{
        setHotWord(state,nv){
            state.hotWord=nv;
        },
        setSearch(state,nv){
            state.search=nv;
        },
        initHistory(state,nv){
            state.history=nv;
        },
        setHistory(state,nv){
            let i=state.history.indexOf(nv);
            if(i==-1){
                state.history.unshift(nv);
                localStorage.setItem("history",JSON.stringify(state.history));
            };
        }
    },
    actions:{
        loadHotWordAndSearch({commit,dispatch}){
            api.loadSearchWord({
                platform: "H5",
                code: "hotWord,sketch"
            }).then((data)=>{
                // console.log(data);
                if(!data.success){
                    return Promise.reject("网络错误!");
                };
                commit("setHotWord",data.data.hotWord.data);
                commit("setSearch",data.data.sketch.data.query);
            }).catch(api.showError);
        },
        loadHistory({commit}){
            if(!localStorage.getItem("history")){
                return;
            };
            let arr=JSON.parse(localStorage.getItem("history"));
            if(arr){
                commit("initHistory",arr);
            }else{
                commit("initHistory",[]);
            };
        }
    },
    modules:{
        home,
        classify,
        searchPage,
        detail
    }
});